<template>
  <el-container>
    <el-header>
      <div class="report_header" ref="headerHeight">
        <div class="report_header_left"></div>
        <div
          style="
            width: 300px;
            display: flex;
            align-items: center;
            margin-left: 10px;
          "
        >
          <svg-icon class="primary" :icon-class="$route.meta.icon" />
          <span style="margin-left: 5px" class="primary">{{
            $route.meta.title
          }}</span>
        </div>
        <div
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            width: 100%;
          "
        >
          <div
            style="
              display: flex;
              flex-direction: row;
              flex-wrap: wrap;
              overflow: hidden;
              height: 41px;
              justify-content: flex-end;
            "
          >
            <div
              class="report_header_query"
              v-if="mchType == 0 || mchType == 3"
            >
              <el-select
                v-model="query.sysMchId"
                clearable
                placeholder="请选择商户"
                style="margin-left: 20px"
                filterable
                value-key="id"
                :filter-method="querySysmch"
                @change="changeSysMch"
              >
                <el-option
                  v-for="item in mchIdOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div class="report_header_query">
              <el-input
                prefix-icon="el-icon-search"
                placeholder="请输入运费名称"
                v-model="query.name"
              ></el-input>
            </div>
          </div>
          <el-button
            style="margin-left: 10px; margin-top: 5px"
            size="small"
            type="primary"
            @click="queryAd"
            >查询</el-button
          >
          <el-button
            style="margin-left: 10px; margin-top: 5px"
            size="small"
            type="primary"
            @click="addClick"
            v-permission="['freight.add']"
            >新增</el-button
          >
        </div>
      </div>
    </el-header>
    <div class="pd10">
      <el-table
        :data="freightList"
        border
        :height="curHeight"
        v-loadMore="[payLoads, 'freight-list']"
        :header-cell-style="{'text-align':'center'}"
      >
        <el-table-column label="排序" type="index" width="56px" align="center">
        </el-table-column>
        <el-table-column label="运费名称" align="center" prop="name">
        </el-table-column>
        <el-table-column label="运费类型" align="center" prop="type" width="80">
          <template slot-scope="{ row }">
            <span>{{ row.type | watchType }}</span>
          </template>
        </el-table-column>

        <el-table-column label="运费" align="left" prop="ykg" width="500">
          <template slot-scope="{ row }" >
            <span style='margin-left:10px' v-if="row.type == 2">{{
              "起步" +
              row.ykg +
              "公里之内" +
              row.ykgPrice +
              "元 ，每增加1公里加收" +
              row.ctdPrice +
              "元"
            }}</span>
            <span style='margin-left:10px' v-if="row.type == 1">{{
              "起步" +
              row.ykg +
              "件之内" +
              row.ykgPrice +
              "元 ，每增加1件加收" +
              row.ctdPrice +
              "元"
            }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="包装费(元/每件)"
          align="center"
          prop="packagingFee"
          width="150"
        >
        </el-table-column>

        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top-start"
                v-permission="['freight.edit']"
              >
                <a @click="editClick(scope.row)">
                  <i style="color: #409eff" class="el-icon-edit"></i>
                </a>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top-start"
                v-permission="['freight.del']"
              >
                <a style="margin-left: 10px" @click="deleteAd(scope.row)">
                  <i style="color: #f56c6c" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--新增标签-->
      <addFreight ref="addFreight" @loadFreight="loadFreight"></addFreight>
      <!--编辑标签-->
      <el-dialog
        title="编辑运费"
        v-el-drag-dialog
        :visible.sync="editVisible"
        width="550px"
      >
        <el-container>
          <el-main class="popup_content">
            <el-form
              ref="editFreight"
              :model="editFreight"
              :rules="rules"
              size="mini"
              label-width="90px"
            >
              <el-form-item label="运费名称" prop="name">
                <el-input
                  v-model="editFreight.name"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="运费类型" prop="status">
                <el-select
                  v-model="editFreight.type"
                  placeholder="请选择类型"
                  style="width: 150px"
                >
                  <el-option
                    v-for="item in freightType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div
                class="freightsettings"
                style="
                  font-weight: 600;
                  margin-left: 25px;
                  color: rgb(96, 98, 102);

                  margin-bottom: 20px;
                "
                v-if="editFreight.type === 2"
              >
                <span>起步</span
                ><el-input
                  v-model="editFreight.ykg"
                  style="width: 50px"
                  type="number"
                ></el-input>
                <span>公里之内</span>
                <el-input
                  v-model="editFreight.ykgPrice"
                  style="width: 50px"
                  type="number"
                ></el-input
                ><span>元</span> <span>，每增加1公里加收</span>
                <el-input
                  v-model="editFreight.ctdPrice"
                  style="width: 50px"
                  type="number"
                ></el-input
                ><span>元</span>
              </div>
              <div
                class="freightsettings"
                style="
                  font-weight: 600;
                  margin-left: 25px;
                  color: rgb(96, 98, 102);
                  margin-bottom: 20px;
                "
                v-if="editFreight.type ==1"
              >
                <span>起步</span
                ><el-input
                  v-model="editFreight.ykg"
                  style="width: 50px"
                  type="number"
                ></el-input>
                <span>件之内</span>
                <el-input
                  v-model="editFreight.ykgPrice"
                  style="width: 50px"
                  type="number"
                ></el-input
                ><span>元</span> <span>，每增加1件加收</span>
                <el-input
                  v-model="editFreight.ctdPrice"
                  style="width: 50px"
                  type="number"
                ></el-input
                ><span>元</span>
              </div>

              <el-form-item label="包装费" prop="packagingFee	">
                <el-input
                  v-model="editFreight.packagingFee"
                  style="width: 150px"
                  type="number"
                ></el-input><span style='margin-left:10px; font-weight: 600;'>(元/每件)</span>
              </el-form-item>

              <!-- </el-main> -->
            </el-form>
          </el-main>
        </el-container>
        <div slot="footer" class="dialog-footer">
          <el-row>
            <!-- <el-col :span="2"><el-button type="primary" :loading="clicked" @click="addEditCity()">添加</el-button></el-col> -->
            <el-col :span="22"
              ><el-button @click="editVisible = false">取 消</el-button>
              <el-button
                type="primary"
                :loading="clicked"
                @click="updateFreight('editFreight')"
                >确 定</el-button
              >
            </el-col>
          </el-row>
        </div>
      </el-dialog>
    </div>
    <el-footer class="el-footerBox">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="loadFreight"
      ></pagination>
    </el-footer>
  </el-container>
</template>

<script>
import { EventBus } from "@/api/eventBus";
import addFreight from "./add";
import Pagination from "@/components/Pagination";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import province from "../../components/Distpicker/province";
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { list, save, del, find, update } from "../../api/freight";
import loadMore from "@/utils/loadMore.js";
import { getInfo, list as sysMchList } from "@/api/sysMch";
export default {
  directives: { elDragDialog, permission, loadMore },
  name: "freight-list",
  activated() {
    this.payLoads = new Date().getTime();
  },
  data() {
    return {
      times: null,
      payLoads: "",
      freightType: [
        {
          value: 1,
          label: "计件",
        },
        {
          value: 2,
          label: "距离",
        },
      ],
      mchIdOptions: [],
      mchType: "",
      editVisible: false,
      clicked: false,
      enterpriseId: "",
      addFreight: {
        type: 2,
        name: "",
      },
      itemList: [],
      cityName: "",
      freightTable: [],
      id: "",
      freightList: [],
      dialogFormVisible: false,
      total: 0,
      pageNum: 1,
      enabledLevel: "",
      pageSize: 20,
      queryType: true,
      options: [],
      editFreight: {},
      editFreightList: [],
      citys: [],
      editFreights: [],
      query: {
        sysMchId: "",
        name: "",
      },
      keyword: {
        name: "",
      },
      curHeight: null,
      rules: {
        name: [{ required: true, message: "请输入运费名称", trigger: "blur" }],
      },
    };
  },
  created() {
    this.loadMch();
    this.loadSysmch("");
    EventBus.$on("freight-add", (res) => {
      // 监听新增完毕
      // 更新列表数组
      this.loadFreight();
      this.freightList.splice(0, 0, res);
    });
    let cityList = [];
    this.formatCity(province[100000], cityList);
    this.options = cityList;
    this.loadFreight();
  },
  filters: {
    watchCitys(val) {
      this.options.forEach((item) => {
        if (val === item.value) {
          return item.label;
        }
      });
    },
    watchType(val) {
      if (val === 1) {
        return "计件";
      } else if (val === 2) {
        return "距离";
      }
    },
  },
  components: {
    Pagination,
    addFreight,
  },
  mounted() {
    this.beforeMount();
    this.comeIn();
  },
  methods: {
    // arraySpanMethod({ row, column, rowIndex, columnIndex }) {
    //   if (this.freightList[rowIndex].type == 2) {
    //     if (columnIndex === 3) {
    //       return [1, 4];
    //     } else if (
    //       columnIndex === 4 ||
    //       columnIndex === 5 ||
    //       columnIndex === 6
    //     ) {
    //       return [0, 0];
    //     }
    //   }
    // },

    loadSysmch(query) {
      sysMchList({ name: query })
        .then((res) => {
          this.mchIdOptions = res.data.data.filter((val) => {
            return val.mchType === 3 || val.mchType === 1;
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changeSysMch() {
      this.loadFreight();
    },
    querySysmch(query) {
      this.loadSysmch(query);
    },
    loadMch() {
      getInfo().then((res) => {
        this.mchType = res.data.mchType;
      });
    },
    cancel() {
      this.dialogFormVisible = false;
      this.addFreight.name = "";
      this.freightTable = [];
    },
    delFreightTable(index) {
      this.editFreightList.splice(index, 1);
    },
    finFreight() {
      find(this.editFreight.id).then((res) => {
        this.editFreight = res.data.freight;
        console.log(this.editFreight);
        //   this.id=this.editFreight.id
        //  this.enterpriseId=this.editFreight.enterpriseId
      });
    },
    // finFreight(){
    //   find(this.editFreight.id).then(response=>{
    //       this.editFreight=response.data.freight
    //       this.id=this.editFreight.id
    //       this.enterpriseId=this.editFreight.enterpriseId
    //       var editFreight={
    //         ctd:this.editFreight.ctd,
    //         enterpriseId: this.enterpriseId,
    //         ctdPrice:this.editFreight.ctdPrice,
    //         ykg:this.editFreight.ykg,
    //         ykgPrice:this.editFreight.ykgPrice,
    //         enabledLevel:this.editFreight.enabledLevel,
    //         levelStart:this.editFreight.levelStart,
    //         levelFreight:this.editFreight.levelFreight,
    //       }
    //       this.editFreightList.push(editFreight)
    //       this.editFreightList=this.editFreightList.concat(this.editFreight.itemList)
    //       this.editFreightList.forEach(item=>{
    //         item.areaId=JSON.stringify(item.areaId)
    //       })
    //       this.editFreights=this.editFreightList
    //   })
    // },
    editClick(row) {
      this.editFreightList = [];
      this.editFreight.id = row.id;
      this.editVisible = true;

      this.finFreight();
    },
    deleteAd(data) {
      var _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          del(data.id)
            .then((response) => {
              console.log(response);
              _this.freightList.forEach(function (item, index) {
                if (item.id == data.id) {
                  _this.freightList.splice(index, 1);
                }
              });
              _this.$message({
                message: response.content,
                offset: 120,
                center: true,
              });
            })
            .catch((error) => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },
    loadFreight() {
      let params = new URLSearchParams();
      params.append("pageNum", this.pageNum);
      params.append("mchId", this.query.sysMchId);
      params.append("pageSize", this.pageSize);
      params.append("name", this.keyword.name);
      list(params).then((response) => {
        this.total = response.data.total;
        this.freightList = response.data.data;
      });
    },
    // addEditCity(){
    //   var freightTable={
    //     createDate:new Date(),
    //     // modifyDate:new Date(),
    //     type:this.addFreight.type,
    //     ykg:'',
    //     levelFreight:0,
    //     enabledLevel:this.enabledLevel,
    //     ctd:'',
    //     ctdPrice:'',
    //     levelStart:0,
    //     ykgPrice:'',
    //   }
    //   this.editFreightList.push(freightTable)
    // },
    resetAd() {
      this.query.name = "";
      this.keyword = this.query;
      this.pageNum = 1;
      this.loadFreight();
    },
    queryAd() {
      this.keyword = this.query;
      this.pageNum = 1;
      this.loadFreight();
    },
    updateFreight(editFreight) {
      this.$refs[editFreight].validate((valid) => {
        if (valid) {
          this.clicked = true;
          if (this.editFreight.levelFreight > 0) {
            this.editFreight.enabledLevel = true;
          } else {
            this.editFreight.enabledLevel = false;
          }
          console.log(this.editFreight);

          this.editFreight.ctd = 1;

          update(this.editFreight)
            .then((response) => {
              this.clicked = false;
              this.editVisible = false;
              this.loadFreight();
              console.log(response);
            })
            .catch((error) => {
              this.clicked = false;
            })
            .catch((error) => {
              this.clicked = false;
            });
        }
      });
    },

    formatCity(ARR, array) {
      for (const key in ARR) {
        let obj = {};
        obj.value = key;
        obj.label = ARR[key];
        array.push(obj);
        if (province[key]) {
          obj.children = [];
          this.formatCity(province[key], obj.children);
        }
      }
    },

    // updateFreight(editFreight){
    //   this.$refs[editFreight].validate((valid) =>{
    //     if (valid){
    //       this.clicked=true
    //       this.citys=this.editFreightList[0]
    //       let freight={
    //         name:this.editFreight.name,
    //         id:this.id,
    //         type:this.editFreight.type,
    //         // modifyDate:new Date(),
    //         enabledLevel:'',
    //         ykg:'',
    //         enterpriseId:this.enterpriseId,
    //         levelFreight:0,
    //         ctd:'',
    //         ctdPrice:'',
    //         levelStart:0,
    //         ykgPrice:'',
    //         itemList:[]
    //       }
    //       if (freight.levelStart){
    //         this.enabledLevel=true
    //       }else {
    //         this.enabledLevel=false
    //       }
    //       freight.ykg=this.citys.ykg
    //       freight.levelFreight=this.citys.levelFreight
    //       freight.ctd=this.citys.ctd
    //       freight.ctdPrice=this.citys.ctdPrice
    //       freight.levelStart=this.citys.levelStart
    //       freight.ykgPrice=this.citys.ykgPrice
    //       // this.editFreights.shift()
    //       // freight.itemList=this.editFreights
    //       if (this.editFreights.length>1){
    //         this.editFreights.splice(0,1)
    //         freight.itemList=this.editFreights
    //       }
    //       // if (freight.itemList.length==1){
    //       //   freight.itemList[0].areaId=''
    //       // }
    //       freight.itemList.forEach(item=>{
    //         item.type=freight.type
    //         if (item.levelStart){
    //           item.enabledLevel=true
    //         }else{
    //           item.enabledLevel=false
    //         }
    //       })
    //       console.log(freight)
    //       if (freight.ykg===''||freight.ctd===''||freight.ctdPrice===''||freight.ykgPrice===''){
    //         this.$message.error('请完善运费模板信息');
    //         this.clicked=false
    //         return
    //       }else{
    //         update(freight).then(response=>{
    //           this.clicked=false
    //           this.editVisible=false
    //           this.loadFreight()
    //         }).catch(error=>{
    //           this.clicked=false
    //         })
    //       }

    //     }
    //   })
    // },
    // formatCity(ARR,array){
    //   for (const key in ARR) {
    //     let obj={}
    //     obj.value=key;
    //     obj.label=ARR[key];
    //     array.push(obj);
    //     if(province[key]){
    //       obj.children=[]
    //       this.formatCity(province[key],obj.children)
    //     }
    //   }
    // },

    deleteFreightTable(index) {
      this.freightTable.splice(index, 1);
    },
    addClick() {
      this.$refs.addFreight.clean();
      this.$refs.addFreight.clicked = false;
      this.$refs.addFreight.dialogFormVisible = true;
      this.$refs.addFreight.addFreightClick();
      // this.$refs.addFreight.getnull()
    },
    beforeMount() {
      var _this = this;
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            _this.curHeight = h - 266; //减去页面上固定高度height
          } else {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            _this.curHeight = h - 220; //减去页面上固定高度height
          }
        })();
      };
    },
    comeIn() {
      console.log("222");
      var h =
        document.documentElement.clientHeight || document.body.clientHeight;
      this.curHeight = h - 220; // 减去页面上固定高度height
    },
    chooseClick() {
      this.queryType = !this.queryType;
      if (this.queryType == false) {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 266; //减去页面上固定高度height
      } else {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220; //减去页面上固定高度height
      }
    },
  },
};
</script>

<style scoped>
.freightsettings span {
  margin-left: 5px;
  margin-right: 5px;
}
.popup_content {
  padding-bottom: 0px !important;
}
.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
  border-top: 1px solid #eeeeee;
}

/deep/ .el-dialog__header {
  border: 1px solid #eeeeee !important;
  padding: 15px !important;
}

/deep/ .el-dialog__body {
  padding: 0px 20px !important;
  margin-top: 20px;
  margin-bottom: 10px;
}
/deep/.el-main {
  padding: 0;
}
.app {
  background-color: rgba(248, 248, 248, 0.8);
}
/deep/.el-header {
  padding: 10px;
  /* height: 100% !important; */
  padding-bottom: 0;
}
.report_header {
  width: 100%;
  min-height: 40px;
  box-sizing: border-box;
  background-color: rgba(248, 248, 248, 0.8);
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}

.report_header_left {
  width: 5px;
  height: 100%;
  background-color: #409eff;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.report_header_query {
  margin-left: 10px;
  width: 180px;
  margin-top: 5px;
}
</style>
